package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.R.integer;
import android.app.Activity;
import android.content.Intent;

import com.flyco.animation.NewsPaperEnter;
import com.google.gson.Gson;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.bean.AddLeaveResponse;
import com.ycsj.goldmedalnewconcept.bean.SumCommentResp;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.pickerview.view.TimePickerView;
import com.ycsj.goldmedalnewconcept.pickerview.view.TimePickerView.OnTimeSelectListener;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.view.ChangeDatePopwindow;
import com.ycsj.goldmedalnewconcept.R;

//在线请假
public class LeaveActivity extends Activity implements OnClickListener {

	//发送请假通知的广播Action
	public static final String ACTION_LEAVE = "LeaveActivity";

	private TextView selectDate;
	private TextView selectDateEnd;
	private TextView tv_count;
	private TextView tv_submit;
	private ImageView iv_back;
	private EditText et_leave;
	private int approval;
	private int noapproval;

	// 记录请假的开始时间和结束时间
	public Date beginDate, endDate;

	public String begindate, enddate;

	// 选择时间的时间选择器
	private TimePickerView pvTime;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_leave);
		selectDate = (TextView) findViewById(R.id.selectDate);
		selectDateEnd = (TextView) findViewById(R.id.selectDateEnd);
		tv_count = (TextView) findViewById(R.id.tv_count);
		tv_submit = (TextView) findViewById(R.id.tv_submit);
		iv_back = (ImageView) findViewById(R.id.iv_back);
		et_leave = (EditText) findViewById(R.id.et_leave);

		approval = getIntent().getIntExtra("approval", 0);
		noapproval = getIntent().getIntExtra("noapproval", 0);
		tv_count.setText("已批准" + approval + "次，待批准 " + noapproval + "次");

		// 设置点击事件
		selectDate.setOnClickListener(this);
		selectDateEnd.setOnClickListener(this);
		iv_back.setOnClickListener(this);
		tv_submit.setOnClickListener(this);
	}

	/**
	 * 判断选择请假时间起始的正确性和上传请假信息
	 */
	private void judgeAndPost() {
		// 如果选择的结束时间小于请假的开始时间,不允许
		
		if(endDate==null||beginDate==null){
			Toast.makeText(LeaveActivity.this, "请选择请假起始时间", 0).show();
			return;
		}
//		
//		if (endDate.getTime() <= beginDate.getTime()) {
//
//			Toast.makeText(LeaveActivity.this, "请假的结束时间必须大于请假的开始时间", 0).show();
//			return;
//		}

		String content = et_leave.getText().toString().trim();

		if (TextUtils.isEmpty(content)) {
			Toast.makeText(LeaveActivity.this, "请输入请假缘由", 0).show();
			return;
		}

		if (containsEmoji(content)) {
			Toast.makeText(LeaveActivity.this, "内容包含无法识别的字符，请重新编辑", 0).show();
			return;
		}

		// 提交数据
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		Date curDate = new Date(System.currentTimeMillis());// 获取当前时间
		Date tomorrowDate = new Date(System.currentTimeMillis() + 86400000);// 获取当前时间
																			// tomorrow
		String curstr = formatter.format(curDate);
		String tomorrowstr = formatter.format(tomorrowDate);
		if (begindate == null) {
			begindate = curstr;
		}
		if (enddate == null) {
			enddate = tomorrowstr;
		}

		OkHttpClient mOkHttpClient = new OkHttpClient();
		// 创建一个Request
		final Request request = new Request.Builder().url(
				Constant.SERVER_URL + "ManageMsg?type=12&c="
						+ SPUtil.getString(LeaveActivity.this, "account", "")
						+ "&role="
						+ SPUtil.getString(LeaveActivity.this, "role", "")
						+ "&content=" + content + "&status=0&begindate="
						+ begindate + "&enddate=" + enddate).build();
		Call call = mOkHttpClient.newCall(request);
		call.enqueue(callBack);
	}

	/**
	 * 请求服务的回调方法
	 */
	Callback callBack = new Callback() {

		@Override
		public void onFailure(Request arg0, IOException arg1) {
			runOnUiThread(new Runnable() {
				public void run() {
					Toast.makeText(LeaveActivity.this, "网络错误", 0).show();
				}
			});
		}

		@Override
		public void onResponse(Response arg0) throws IOException {
			String json = arg0.body().string();
			Log.e("test", json);
			Gson gson = new Gson();
			if (!("{\"state\":\"-1\"}").equals(json)) {
				final AddLeaveResponse fromJson = gson.fromJson(json,
						AddLeaveResponse.class);

				if ("-1".equals(fromJson.state)) {

					runOnUiThread(new Runnable() {
						public void run() {
							Toast.makeText(LeaveActivity.this,
									"提交失败，请确认账号是否关联老师", 0).show();
						}
					});
				}

				if ("0".equals(fromJson.state)) {

					runOnUiThread(new Runnable() {
						public void run() {
							Toast.makeText(LeaveActivity.this,
									"抱歉，没有找到与您关联的老师", 0).show();
						}
					});

				}

				if ("1".equals(fromJson.state)) {

					runOnUiThread(new Runnable() {
						public void run() {

							Toast.makeText(LeaveActivity.this, "申请已提交成功", 0)
									.show();
							tv_count.setText("已批准" + approval + "次，待批准 "
									+ (noapproval + 1) + "次");

							// 发送一个广播,通知请假列表界面进行刷新
							Intent intent = new Intent(ACTION_LEAVE);
							sendBroadcast(intent);
							finish();
						}
					});
				}
			} else {

				runOnUiThread(new Runnable() {
					public void run() {
						Toast.makeText(LeaveActivity.this, "服务器开小差了", 0).show();
					}
				});
			}
		}
	};

	/**
	 * 工具方法,判断输入的请假内容是否包含特殊字符
	 * 
	 * @param source
	 * @return
	 */

	public boolean containsEmoji(String source) {
		int len = source.length();
		for (int i = 0; i < len; i++) {
			char codePoint = source.charAt(i);
			if (!isEmojiCharacter(codePoint)) { // 如果不能匹配,则该字符是Emoji表情
				return true;
			}
		}
		return false;
	}

	private boolean isEmojiCharacter(char codePoint) {
		return (codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
				|| (codePoint == 0xD)
				|| ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
				|| ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
				|| ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
	}

	/**
	 * 点击事件
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.selectDate:
			// 选择开始时间
			showTimePop(1);
			break;

		case R.id.selectDateEnd:
			// 选择结束时间
			showTimePop(2);
			break;

		case R.id.iv_back:
			// 返回
			finish();
			break;
		case R.id.tv_submit:
			// 提交
			judgeAndPost();
			break;
		default:
			break;
		}
	}

	/**
	 * 弹出选择时间的PopUpWindow
	 */
	private void showTimePop(final int flag) {
		// 设置只显示年月
		pvTime = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);

		// 设置起始年月
		pvTime.setRange(Calendar.getInstance().get(Calendar.YEAR), Calendar
				.getInstance().get(Calendar.YEAR) + 15);

		pvTime.setTime(new Date());

		pvTime.setCyclic(false);

		pvTime.setCancelable(true);

		// 设置时间选中监听
		pvTime.setOnTimeSelectListener(new OnTimeSelectListener() {

			@Override
			public void onTimeSelect(Date date) {
				// 格式化选择的时间,转化成字符串
				SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

				String res = sf.format(date);

				if (flag == 1) {
					// 表示选择开始时间
					begindate = res;
					beginDate = date;
					selectDate.setText(res);
				} else if (flag == 2) {
					// 表示选择结束时间
					enddate = res;
					endDate = date;
					selectDateEnd.setText(res);
				}
			}
		});

		pvTime.show();
	}

}
